<template>
  <div>
    <div class="search_box">
      <el-form :inline="true" :model="formData">
        <el-form-item label="分销商">
          <el-select
            v-model="formData.tenantId"
            filterable
            placeholder="请选择分销商"
            @change="changeTenantId"
            clearable
          >
            <el-option
              v-for="item in distriOption"
              :key="item?.id"
              :label="item.label"
              :value="item?.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="剧目名称">
          <el-input
            v-model="formData.operaName"
            placeholder="剧目名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList(1)">查 询</el-button>
          <el-button type="primary" @click="resetList">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <div class="table_top">
        <div>
          <el-radio-group
            v-model="formData.appId"
            @change="changeAppId"
            v-if="appsList.length"
          >
            <el-radio-button
              v-for="item in appsList"
              :key="item?.id"
              :label="item.id"
            >
              {{ item?.appName }}
            </el-radio-button>
          </el-radio-group>
        </div>
        <div style="margin-right: 98px">
          <el-button type="primary" @click="syncEpisode">
            <el-icon style="margin-right: 5px">
              <Refresh />
            </el-icon>
            同步剧目
          </el-button>
          <el-button type="primary" @click="addEps">
            <el-icon style="margin-right: 5px">
              <Plus />
            </el-icon>
            添加剧目
          </el-button>
        </div>
      </div>

      <custom-table
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
        :isCustomHead="true"
        class="table_box"
      >
        <template #desc="{ scope }">
          <el-tooltip
            effect="dark"
            :content="scope.row.desc"
            placement="top"
            v-if="scope.row?.desc && scope.row?.desc.length > 17"
          >
            <div class="overflowTwo name">{{ scope.row.desc }}</div>
          </el-tooltip>
          <div class="overflowTwo name" v-else>{{ scope.row.desc }}</div>
        </template>
        <template #showStatus="{ scope }">
          <el-switch
            style="

--el-switch-on-color: #13ce66"
            :modelValue="scope.row.showStatus === 1"
            inline-prompt
            active-text="是"
            inactive-text="否"
            @click.stop="handdelStatus(scope.row)"
          />
        </template>
        <template #updateEpisodeNo="{ scope }">
          {{ `${scope.row?.updateEpisodeNo} / ${scope.row?.episodeNum}` }}
        </template>
        <template #promotionStartTime="{ scope }">
          <span v-if="activeTime(scope.row?.promotionStartTime)" class="red">
            {{ scope.row?.promotionStartTime }}
          </span>
          <el-tag type="success" v-else>已开投</el-tag>
        </template>
        <template #scopeList="{ scope }">
          <span v-if="scope.row?.scopeList && scope.row?.scopeList.length > 0">
            <el-tag
              v-for="(item, index) in scope.row?.scopeList"
              :key="index"
              style="margin-right: 6px"
              >{{ item }}
            </el-tag>
          </span>
        </template>
        <template #operator="{ scope }">
          <!-- <span
            class="operationClick"
            @click.stop="handleActive(scope.row, '授权')"
          >
            分销商授权
          </span> -->
          <span
            class="operationClick"
            @click.stop="handleActive(scope.row, '取消')"
          >
            取消授权
          </span>
          <span
            class="operationClick"
            @click.stop="handleActive(scope.row, '卡点')"
          >
            修改卡点
          </span>
        </template>
      </custom-table>
    </div>

    <!-- 分销商添加剧目授权-->
    <powerDialog ref="addEpisodeRef" @success="getList(1)" :isMultiple="true" />

    <!-- 同步分销商 -->
    <distributor
      ref="distributorRef"
      @success="getList(1)"
      :isMultiple="true"
      :title="'同步剧目到分销商'"
      :btnText="'同步'"
      :batchBtnText="'批量同步'"
      :typePower="3"
    />

    <!-- 设置最大卡点 -->
    <episodeLimit ref="limitRef" @success="getList(1)" />
  </div>
</template>

<script setup lang="ts">
import distributor from "@/components/Distributor/index.vue";
import customTable from "@/components/CustomTable/index.vue";
import powerDialog from "./components/powerDialog.vue";
import episodeLimit from "./components/episodeLimit.vue";

import {
  searchOperas,
  configShowStatus,
} from "@/api/operateCenter/distributorEpisode/index";
import { searchTenant } from "@/api/operateCenter/distributor/index";
import { getBindedAppslist } from "@/api/operateCenter/distributor/index";
import { deleteAgentDistributor } from "@/api/operateCenter/episode/index";
import type { Action } from "element-plus";
import moment from "moment";
import { reactive, ref } from "vue";
import { Plus, Refresh, QuestionFilled } from "@element-plus/icons-vue";
import router from "@/router";

const loading = ref<boolean>(false);
const tableData = ref<Array<any>>([]);
const distriOption = ref<Array<any>>([]);
const appsList = ref<Array<any>>([]);

const form = {
  tenantId: "",
  appId: 0,
  operaName: "",
  pageNo: 1,
  pageSize: 10,
};

const formData = reactive(Object.assign({}, form));
interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const columns = reactive([
  { label: "剧目Id", prop: "operaId", minWidth: 80 },
  { label: "剧目", prop: "name", minWidth: 100 },
  { label: "备注", prop: "desc", slotName: "desc", minWidth: 150 },
  {
    label: "开投时间",
    prop: "promotionStartTime",
    slotName: "promotionStartTime",
    minWidth: 160,
  },
  {
    label: "能力",
    prop: "scopeList",
    slotName: "scopeList",
    minWidth: 160,
  },
  {
    label: "已发布/总集数",
    prop: "updateEpisodeNo",
    slotName: "updateEpisodeNo",
    minWidth: 115,
  },
  { label: "默认收费卡点", prop: "chargeEpisodeNo", minWidth: 110 },
  { label: "最大收费卡点", prop: "chargeEpisodeNoUpperLimit", minWidth: 110 },
  { label: "默认单价(金币)", prop: "unblockCoinAmount", minWidth: 118 },
  { label: "最小单价(金币)", prop: "unblockCoinAmountMinLimit", minWidth: 118 },
  {
    label: "小程序名称",
    prop: "app",
    minWidth: 150,
    formatter: (row: Record<string, any>) => {
      return row?.app?.appName;
    },
  },
  {
    label: "小程序展示",
    prop: "showStatus",
    slotName: "showStatus",
    minWidth: 150,
  },
  {
    label: "操作",
    prop: "operator",
    slotName: "operator",
    fixed: "right",
    width: 160,
  },
]);

// 切换分销商 重新查询列表
const changeTenantId = (id: any) => {
  formData.tenantId = id;
  if (id) {
    getAllocatedApps();
  }
};

// 开关
const handdelStatus = (val: Record<string, any>) => {
  ElMessageBox.alert(
    `确定要${val?.showStatus == 1 ? "隐藏" : "展示"} "${
      val?.name
    }"剧目绑定的小程序吗？`,
    "提醒",
    {
      confirmButtonText: "确定",
      callback: (action: Action) => {
        if (action === "confirm") {
          let params = {
            id: val.id,
            showStatus: val.showStatus ? 0 : 1,
          };
          configShowStatus(params).then(() => {
            ElMessage.success(`${val?.showStatus ? "隐藏" : "展示"}成功`);
            getList(1);
          });
        }
      },
    }
  );
};

// 切换小程序 查询列表
const changeAppId = (val: any) => {
  formData.appId = val;
  getList();
};

// 获取分销商已分配的小程序
const getAllocatedApps = () => {
  getBindedAppslist({ tenantId: Number(formData.tenantId) }).then(
    (res: any) => {
      appsList.value = res || [];
      if (res.length) {
        formData.appId = appsList.value[0]?.id;
        getList();
      } else {
        tableData.value = [];
        pageObj.total = 0;
      }
    }
  );
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.pageNo = pageObj.pageNo;
  //   formData.pageSize = pageObj.pageSize;
  // } else {
  //   formData.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.pageSize = pageObj.pageSize = val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.pageNo = pageObj.pageNo;
  formData.pageSize = pageObj.pageSize;

  if (!formData.tenantId || !formData.appId) return;
  loading.value = true;
  searchOperas(formData)
    .then((res: Record<string, any>) => {
      tableData.value = res?.data.map((item: Record<string, any>) => {
        item.premiereTime = moment(item.premiereTime + "Z").format(
          "YYYY-MM-DD HH:mm:ss"
        );
        item.promotionStartTime = moment(item.promotionStartTime + "Z").format(
          "YYYY-MM-DD HH:mm:ss"
        );
        item.scopeList = item.scopeList ? item.scopeList.split(",") : [];
        return item;
      });
      pageObj.total = Number(res?.total);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 获取分销商
const getTenantList = () => {
  searchTenant({ pageNo: 1, pageSize: 999 }).then(
    (res: Record<string, any>) => {
      distriOption.value = res?.data.map((item: Record<string, any>) => {
        return {
          label: item?.name,
          value: item?.id.toString(),
        };
      });
    }
  );
};

// 同步剧目
const distributorRef = ref();
const syncEpisode = () => {
  if (!formData.tenantId) return ElMessage.error("请先选择分销商");
  if (!formData.appId)
    return ElMessage.error("该分销商下没有小程序，无法同步剧目");
  let params = {
    sourceAgentId: formData.tenantId,
    sourceAppId: formData.appId,
  };
  distributorRef.value.showDialog(params);
};

// 新增
const addEpisodeRef = ref();
const addEps = () => {
  if (!formData.tenantId) return ElMessage.error("请先选择分销商");
  addEpisodeRef.value.showDialog(formData.tenantId);
};

// 取消分销商授权
const limitRef = ref();
const handleActive = (val: Record<string, any>, str: string) => {
  if (str === "取消") {
    let appnames = appsList.value.map((item: Record<string, any>) => {
      return item?.appName;
    });
    console.log("appnames---", appnames);
    ElMessageBox({
      title: "提醒",
      message: h("p", null, [
        h("p", null, `确定要取消"${val?.name}"剧目授权吗？`),
        h("span", null, `此操作包含 `),
        h("span", { style: "color: #ff4949" }, `${appnames}`),
        h("span", null, ` 小程序中的剧目都会取消授权。`),
      ]),
      confirmButtonText: "确定",
      beforeClose: (action, instance, done) => {
        if (action === "confirm") {
          let params = {
            operaId: val.operaId,
            agentIds: [formData.tenantId],
          };
          deleteAgentDistributor(params).then(() => {
            ElMessage.success(`取消成功`);
            getList(1);
            done();
          });
        } else {
          done();
        }
      },
    });
  } else if (str === "卡点") {
    limitRef.value.showDialog(val);
  }
};

// 重置
const resetList = () => {
  Object.assign(formData, form);
  tableData.value = appsList.value = [];
  pageObj.total = 0;
};

// 开投时间
const activeTime = (Time: string) => {
  let now = Date.now();
  let openTime = moment(Time).valueOf();
  return openTime > now ? true : false;
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

onMounted(() => {
  getTenantList();
});
</script>

<style lang="scss" scoped>
.table_box_wrapper {
  padding-top: 10px;
  margin-top: 15px;
  background-color: #fff;

  .allocation_app {
    padding: 12px 0 5px 10px;
  }

  .hover_text {
    cursor: pointer;
  }

  .hover_text:hover {
    text-decoration: underline;
  }

  .table_top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 12px;
  }
}

.table_box {
  padding: 10px;
  border-radius: 4px;

  .movie_box {
    display: flex;
    align-items: center;

    img {
      width: 72px;
      height: 108px;
      margin-right: 12px;
    }
  }

  .icon_header {
    margin-left: 2px;
    font-size: 15px;
    vertical-align: text-top;
  }
}
</style>
